/**
 * 公共JS.
 * User: zhaoming
 * Date: 15-8-18
 * Time: 上午11:47
 * To change this template use File | Settings | File Templates.
 */
Date.prototype.format = function(format) {
    var o = {
        "M+" :this.getMonth() + 1,
        "d+" :this.getDate(),
        "h+" :this.getHours(),
        "m+" :this.getMinutes(),
        "s+" :this.getSeconds(),
        "q+" :Math.floor((this.getMonth() + 3) / 3),
        "S" :this.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};


/**
 * 多级联动组件
 * @constructor
 */
var Linkage = function(){
    var _data = [];

    /**
     * 设置默认值
     * @param elementId 元素ID
     * @param value 值
     */
    var _setDefaultValue = function(elementId, value){
        $("#"+elementId).select2("val", value);
    };

    var _clear = function(index){
        var i = index + 1;
        while(i < _data.length){
            var linkage = _data[i];
            $("#"+linkage.id).empty();
            $("#"+linkage.id).append("<option value=''>请选择</option>");
            _setDefaultValue(linkage.id, '');
            i++;
        }
    };

    var _load = function(index, linkage){
        var id      = linkage.id;
        var url     = linkage.url;
        var data    = linkage.data || {};
        var code    = linkage.code || "code";
        var name    = linkage.name || "name";
        var value   = linkage.value || '';
        $.ajax({
            url: url,
            dataType: "json",
            type: "POST",
            async:false,
            data: data,
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    $("#"+id).append("<option value='" + data[i][code] + "'>" + data[i][name] + "</option>");
                }
            },
            error: function(data){

            }
        });
    };
    this.init = function(linkages){
        _data = linkages;
        if(linkages != null){
            for(var i=0; i<linkages.length; i++){
                var linkage = linkages[i];
                //绑定事件
                if(i < linkages.length-1){
                    $("#"+linkages[i].id).bind("change", {index: i}, function(event) {
                        var index = event.data.index;
                        _clear(index);
                        if($(this).val() != ""){
                            var linkage = linkages[index + 1];
                            var data = {};
                            data[linkage.parent] = $(this).val();
                            linkage.data = data;
                            _load(index, linkages[index + 1]);
                        }
                    });
                }
                //赋默认值并初始化下拉组件
                if(i == 0){
                    _load(i, linkage);
                }else{
                    var lastLinkage = linkages[i - 1];
                    if(lastLinkage.value != undefined && lastLinkage.value != ""){
                        var data = {};
                        data[linkage.parent] = lastLinkage.value;
                        linkage.data = data;
                        _load(i, linkage);
                    }
                }
                _setDefaultValue(linkage.id, linkage.value);
            }
        }
    };
};

/**
 * 提示框
 * @type {{info, error, warning, success, confirm}}
 */
Alert = (function() {
    return {
        /**
         * 普通提示
         * @param _context_ 内容
         * @param _title_ 标题
         * @param _call_back_ 回调函数
         */
        info: function(_context_, _title_, _call_back_) {
            if (undefined === _title_) {
                _title_ = "提示信息";
            }else{
                if ($.isFunction(_title_)) {
                    _call_back_ = _title_;
                    _title_ = "提示信息";

                }
            }
            layer.alert(_context_, {
                title: _title_,
                skin: 'alert-info-class',
                area: ['350px'],
                btnAlign: 'r',
                anim: 5,
                shade: 0.3,
                cancel: function(){
                    if(_call_back_ !== undefined){
                        _call_back_();
                    }
                }
            }, function(index){
                if(_call_back_ !== undefined){
                    _call_back_();
                }
                layer.close(index);
            });
        },

        /**
         * 错误信息
         * @param _context_ 内容
         * @param _title_ 标题
         * @param _call_back_ 回调函数
         */
        error: function(_context_, _title_, _call_back_) {
            if (undefined === _title_) {
                _title_ = "错误信息";
            }else{
                if ($.isFunction(_title_)) {
                    _call_back_ = _title_;
                    _title_ = "错误信息";

                }
            }
            layer.alert(_context_, {
                title: "提示信息",
                skin: 'alert-error-class',
                icon: 2,
                area: ['350px'],
                btnAlign: 'r',
                anim: 5,
                shade: 0.3,
                cancel: function(){
                    if(_call_back_ !== undefined){
                        _call_back_();
                    }
                }
            }, function(index){
                if(_call_back_ !== undefined){
                    _call_back_();
                }
                layer.close(index);
            });
        },

        /**
         * 警告信息
         * @param _context_ 内容
         * @param _title_ 标题
         * @param _call_back_ 回调函数
         */
        warning: function(_context_, _title_, _call_back_) {
            if (undefined === _title_) {
                _title_ = "警告信息";
            }else{
                if ($.isFunction(_title_)) {
                    _call_back_ = _title_;
                    _title_ = "警告信息";

                }
            }
            layer.alert(_context_, {
                title: "提示信息",
                skin: 'alert-warning-class',
                icon: 0,
                area: ['350px'],
                btnAlign: 'r',
                anim: 5,
                shade: 0.3,
                cancel: function(){
                    if(_call_back_ != undefined){
                        _call_back_();
                    }
                }
            }, function(index){
                if(_call_back_ != undefined){
                    _call_back_();
                }
                layer.close(index);
            });
        },

        /**
         * 成功提示
         * @param _context_ 内容
         * @param _title_ 标题
         * @param _call_back_ 回调函数
         */
        success: function(_context_, _title_, _call_back_) {
            if (undefined == _title_) {
                _title_ = "成功信息";
            }else{
                if ($.isFunction(_title_)) {
                    _call_back_ = _title_;
                    _title_ = "成功信息";

                }
            }
            layer.alert(_context_, {
                title: _title_,
                skin: 'alert-success-class',
                icon: 1,
                area: ['350px'],
                btnAlign: 'r',
                anim: 5,
                shade: 0.3,
                cancel: function(){
                    if(_call_back_ != undefined){
                        _call_back_();
                    }
                }
            }, function(index){
                if(_call_back_ != undefined){
                    _call_back_();
                }
                layer.close(index);
            });
        },

        /**
         * 确认提示
         * @param _context_ 内容
         * @param _title_ 标题
         * @param _ok_call_back_ 确定回调函数
         * @param _cancel_call_back_ 取消回调函数
         */
        confirm : function(_context_, _title_, _ok_call_back_, _cancel_call_back_) {
            if (undefined == _title_) {
                _title_ = "<b>确认信息</b>";
            }else{
                if ($.isFunction(_title_)) {
                    _cancel_call_back_ = _ok_call_back_;
                    _ok_call_back_ = _title_;
                    _title_ = "<b>确认信息</b>";

                }
            }
            layer.confirm(_context_, {
                title: _title_,
                skin: 'alert-confirm-class',
                area: ['350px'],
                btn: ['确定', '取消'],
                btnAlign: 'c',
                anim: 5,
                shade: 0.3
            }, function(index){
                if(_ok_call_back_ != undefined){
                    _ok_call_back_();
                }
                layer.close(index);
            }, function(index){
                if(_cancel_call_back_ != undefined){
                    _cancel_call_back_();
                }
                layer.close(index);
            });
        },
        /**
         * 加载
         * @param _call_back_ 取消回调函数
         */
        load: function(_call_back_) {
            layer.load(2,
                {shade:0.1},
                function(index){
                    if(_call_back_ != undefined){
                        _call_back_();
                    }
                    layer.close(index);
                });
            }
        }
    }
)();

/**
 * 调整数据列表宽度
 * @param id
 */
function resizeJqGrid(id){
    var grid_selector = "#"+id;
    var parent_column = $(grid_selector).closest('[class*="col-"]');
    //resize to fit page size
    $(window).on('resize.jqGrid', function () {
        $(grid_selector).jqGrid( 'setGridWidth', parent_column.width()-2 );
    });

    //resize on sidebar collapse/expand
    $(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
        if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
            //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
            setTimeout(function() {
                $(grid_selector).jqGrid( 'setGridWidth', parent_column.width()-2 );
            }, 20);
        }
    })
}

/**
 * 修改jqGrid图标
 * @param table
 */
function updatePagerIcons(table) {
    var replacement = {
        'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
        'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
        'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
        'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
    };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

        if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
    })
}

/**
 * 打开导航菜单
 */
function activeNavBar(elementId){
    $("#menus").find("li").each(function(){
        $(this).removeClass("active");
        $(this).removeClass("open");
    });
    $("#menus").find("ul").each(function(){
        $(this).removeClass("nav-show");
        $(this).addClass("nav-hide").hide();
    });
    $("#"+elementId).parents("ul").addClass("nav-show").show();
    $("#"+elementId).parents("ul").parent("li").addClass("active open");
    $("#"+elementId).addClass("active");
}

/**
 * 初始化Select2组件
 */
function initSelect2(){
    $(".form-select2").addClass("width-100").select2().on("select2-close", function (e) {
        $(this).isValid();
    });
}

/**
 * 初始化LayDate组件
 * @param id 元素ID
 * @param type 日期格式
 */
function initLayDate(id, type){
    layui.laydate.render({ elem: '#'+id,type: type, done: function(){
        $("#"+id).isValid();
    }});
}

/**
 * 是否是图片文件
 * @param files
 * @returns {boolean}
 */
function isImageFile(files) {
    for(var i = 0; i < files.length; i++) {
        var file = files[i];
        if( typeof file === 'string') {
            if(!isImage(file)) {
                Alert.warning("只允许jpg、jpeg、png格式的文件上传");
                return false;
            }
        } else if( 'File' in window && file instanceof window.File ) {
            if(file.type != "image/jpg" && file.type != "image/jpeg" && file.type != "image/png" && file.type != "image/gif" ){
                Alert.warning("只允许jpg、jpeg、png格式的文件上传");
                return false;
            }
        }
    }
    return true;
}

/**
 * 是否是图片
 */
function isImage(filename) {
    var flag = false; //状态
    var arr = ["jpg","jpeg","png"];
    //取出上传文件的扩展名
    var index = filename.lastIndexOf(".");
    var ext = filename.substr(index+1);
    //循环比较
    for(var i=0;i<arr.length;i++){
        if(ext == arr[i]){
            flag = true; //一旦找到合适的，立即退出循环
            break;
        }
    }
    return flag;
}

/**
 * 绑定页面跳转功能到windows对象
 */
window.forward = function(url){
    var flag = IEVersion();
    if(flag == "-1" || flag == "11" || flag == "10"){
        $.pjax({
            url: url,
            container: '#pjax-container'
        })
    }else{
        window.location.href = url;
    }
};

/**
 * 判断IE版本
 * @return {string}
 */
function IEVersion() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if(isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if(fIEVersion === 7) {
            return "7";
        } else if(fIEVersion === 8) {
            return "8";
        } else if(fIEVersion === 9) {
            return "9";
        } else if(fIEVersion === 10) {
            return "10";
        } else {
            return "6";//IE版本<=7
        }
    } else if(isEdge) {
        return "edge";//edge
    } else if(isIE11) {
        return "11"; //IE11
    }else{
        return "-1";//不是ie浏览器
    }
}

/**
 * 转义html特殊字符
 * @param str
 */
function escapeHtmlCharacter(str) {
    var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
}